//
//  RegisterViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/4/6.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "RegisterViewController.h"
#import "UIButton+GetCode.h"
#import "NSString+MD5.h"
#import <SMS_SDK/SMSSDK.h>
#import <JPUSHService.h>
#import "UserTabBarViewController.h"
#import "ShopTabBarViewController.h"

@interface RegisterViewController ()
{
    UIImage *chooseImage;
}

Strong UIImageView *titleImageView;
Strong UILabel *titleLabel;
@property (strong, nonatomic) UITextField *nameTextField;
@property (strong, nonatomic) UITextField *phoneTextField;
@property (strong, nonatomic) UITextField *codeTextField;
@property (strong, nonatomic) UITextField *firstTextField;
@property (strong, nonatomic) UITextField *secondTextField;
@property (strong, nonatomic) UITextField *thirdTextField;
@property (strong, nonatomic) UIButton *submitBtn;
Strong UIView *bgView;
@property (nonatomic,strong) UIButton *getCodeBtn;

@end

//网络
@implementation RegisterViewController (NetWorking)

- (void)getData{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"auMobile":self.phoneTextField.text,
                                 @"code":self.codeTextField.text,
                                 @"auPassword":[NSString md5:self.secondTextField.text],
                                 @"payPassword":self.thirdTextField.text
                                 };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Login_Registration/registered.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (chooseImage) {
            NSData *data = UIImageJPEGRepresentation(chooseImage, .1);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
            [formData appendPartWithFileData:data name:@"file" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        if (State(responseObject)) {
        NSLog(@"%@",responseObject);
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            [self login];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

//登录
- (void)login
{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"auMobile":self.phoneTextField.text,@"auPassword":[NSString md5:self.secondTextField.text]};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Login_Registration/validateLogon.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] integerValue] == 0) {
            [UserModel sharedInstanced].userId = [NSString stringWithFormat:@"%@",responseObject[@"obj"][@"id"]];
            [UserModel sharedInstanced].headImg = [NSString stringWithFormat:@"%@",responseObject[@"obj"][@"headPortrait"]];
            [UserModel sharedInstanced].mobile = responseObject[@"obj"][@"tel"];
            [UserModel sharedInstanced].payThePassword = responseObject[@"obj"][@"payPassword"];
            [UserModel sharedInstanced].password = self.secondTextField.text;
            [UserModel sharedInstanced].nameNick = responseObject[@"obj"][@"username"];
            
            [JPUSHService setAlias:[UserModel sharedInstanced].mobile callbackSelector:nil object:nil];
            if ([responseObject[@"obj"][@"type"] integerValue] == 0) {
                UserTabBarViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass([UserTabBarViewController class])];
                vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                [UserModel sharedInstanced].userType = @"0";
                [self presentViewController:vc animated:YES completion:nil];
            }else{
                ShopTabBarViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass([ShopTabBarViewController class])];
                vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                [UserModel sharedInstanced].userType = @"1";
                
                [self presentViewController:vc animated:YES completion:nil];
            }
            
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}


- (void)getsendOutYZM{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"phone":self.phoneTextField.text,
                                 @"judge":@"1"};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Login_Registration/sendOutYZM.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.getCodeBtn start];
            ShowMessage(responseObject[@"msg"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupForDismissKeyboard];
    self.view.backgroundColor = getColor(@"e2f2fc");
     [self.view sd_addSubviews:@[self.bgView , self.titleLabel , self.titleImageView, self.submitBtn]];
    [self layoutFrame];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.navigationController.navigationBar setTranslucent:YES];
    [self.navigationController.navigationBar.subviews firstObject].alpha = 1;
}

#pragma mark - Event

- (void)getCodeEvent{
    if (![TSRegularExpressionUtil validateMobile:self.phoneTextField.text] || [self.phoneTextField.text isEqualToString:@""]) {
        ShowMessage(@"请输入正确的手机号");
        return;
    }
    [self getsendOutYZM];
    
}

- (void)submitEvent{
//    if ([self.nameTextField.text isEqualToString:@""]) {
//        ShowMessage(@"请输入用户名");
//        return;
//    }
//    if (![TSRegularExpressionUtil validateNickname:self.nameTextField.text]) {
//        ShowMessage(@"用户名不能有特殊字段");
//        return;
//    }
    if (![TSRegularExpressionUtil validateMobile:self.phoneTextField.text]) {
        ShowMessage(@"请输入正确的手机号");
        return;
    }
    if (![TSRegularExpressionUtil validateVerifyCode:self.codeTextField.text]) {
        ShowMessage(@"请输入正确的验证码");
        return;
    }
    if ([self.firstTextField.text isEqualToString:@""] || [self.secondTextField.text isEqualToString:@""]) {
        ShowMessage(@"请输入确认密码");
        return;
    }
    if ([self.thirdTextField.text isEqualToString:@""]) {
        ShowMessage(@"请输入支付密码");
        return;
    }
    NSLog(@"%@",self.firstTextField.text);
    NSLog(@"%@",self.secondTextField.text);
    if (![self.firstTextField.text isEqualToString:self.secondTextField.text]) {
        ShowMessage(@"两次密码输入不一致请重新输入");
        return;
    }
    if (!chooseImage) {
        ShowMessage(@"请选择头像");
        return;
    }
    [self getData];
   
}

- (void)changeIconImg:(UITapGestureRecognizer *)sender{
    [self selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) {
        ((UIImageView *)sender.view).image = img;
        chooseImage = img;
    }];
}

#pragma mark - set & get

- (UIImageView *)titleImageView{
    if (!_titleImageView) {
        _titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"add"]];
        //    imgView.backgroundColor = [UIColor whiteColor];
        _titleImageView.frame = CGRectMake(0, 0, 110, 110);
        _titleImageView.center = CGPointMake(SCREEN_WIDTH/2., 120 / WIDTH_5S_SCALE);
        _titleImageView.layer.masksToBounds = YES;
        _titleImageView.layer.cornerRadius = 55;
        _titleImageView.contentMode = UIViewContentModeScaleToFill;
        _titleImageView.userInteractionEnabled = YES;
        [_titleImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeIconImg:)]];
    }
    return _titleImageView;
}

- (UIView *)bgView{
    if (!_bgView) {
        _bgView = [[UIView alloc]initWithFrame:CGRectMake(49 / WIDTH_5S_SCALE, 180 / WIDTH_5S_SCALE, SCREEN_WIDTH - 98 / WIDTH_5S_SCALE, 44  * 5 + 4)];
        _bgView.backgroundColor = getColor(@"ffffff");
        _bgView.layer.masksToBounds = YES;
        _bgView.layer.cornerRadius = 5;
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH - 98 / WIDTH_5S_SCALE, 1)];
        lineView.backgroundColor = getColor(@"e2f2fc");
        
        UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 44  * 2, SCREEN_WIDTH - 98 / WIDTH_5S_SCALE, 1)];
        lineView1.backgroundColor = getColor(@"e2f2fc");
        
        UIView *lineView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 44  * 3, SCREEN_WIDTH - 98 / WIDTH_5S_SCALE, 1)];
        lineView2.backgroundColor = getColor(@"e2f2fc");
        
        UIView *lineView3 = [[UIView alloc]initWithFrame:CGRectMake(0, 44  * 4, SCREEN_WIDTH - 98 / WIDTH_5S_SCALE, 1)];
        lineView3.backgroundColor = getColor(@"e2f2fc");
        
        [_bgView sd_addSubviews:@[self.firstTextField , self.secondTextField,self.phoneTextField, self.codeTextField,self.thirdTextField,lineView , lineView1 , lineView2, lineView3]];
    }
    return _bgView;
}

- (UITextField *)phoneTextField{
    if (!_phoneTextField) {
        _phoneTextField  = [[UITextField alloc]init];
        _phoneTextField.font = DEF_FontSize_14;
        _phoneTextField.textColor = getColor(mainColor);
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"手机号" attributes:
                                          @{NSForegroundColorAttributeName:getColor(mainColor)
                                            }];
        _phoneTextField.attributedPlaceholder = attrString;
        _phoneTextField.leftViewMode = UITextFieldViewModeAlways;
        _phoneTextField.leftView = ({
            UIImageView *imgView = [UIImageView new];
            imgView.frame = CGRectMake(0, 8, 50, 16);
            imgView.contentMode = 1;
            imgView.image = [UIImage imageNamed:@"phoneText"];
            imgView;
        });
    }
    return _phoneTextField;
}

- (UITextField *)codeTextField{
    if (!_codeTextField) {
        _codeTextField  = [[UITextField alloc]init];
        _codeTextField.font = DEF_FontSize_14;
        _codeTextField.textColor = getColor(mainColor);
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"验证码" attributes:
                                          @{NSForegroundColorAttributeName:getColor(mainColor)
                                            }];
        _codeTextField.attributedPlaceholder = attrString;
        _codeTextField.leftViewMode = UITextFieldViewModeAlways;
        _codeTextField.leftView = ({
            UIImageView *imgView = [UIImageView new];
            imgView.frame = CGRectMake(0, 8, 50, 16);
            imgView.contentMode = 1;
            imgView.image = [UIImage imageNamed:@"password"];
            imgView;
        });
        _codeTextField.rightViewMode = UITextFieldViewModeAlways;
        _codeTextField.rightView = ({
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 96, 36)];
            _getCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(12, 6, 72, 24)];
            [_getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [_getCodeBtn setTitleColor:getColor(mainColor) forState:UIControlStateNormal];
            _getCodeBtn.layer.borderColor = getColor(mainColor).CGColor;
            _getCodeBtn.layer.borderWidth = 1;
            _getCodeBtn.layer.masksToBounds = YES;
            _getCodeBtn.layer.cornerRadius = 5;
            [_getCodeBtn addTarget:self action:@selector(getCodeEvent) forControlEvents:UIControlEventTouchUpInside];
            _getCodeBtn.titleLabel.font = DEF_FontSize_10;
            [view addSubview:_getCodeBtn];
            view;
        });

    }
    return _codeTextField;
}

- (UITextField *)firstTextField{
    if (!_firstTextField) {
        _firstTextField  = [[UITextField alloc]init];
        _firstTextField.font = DEF_FontSize_14;
        _firstTextField.textColor = getColor(mainColor);
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"输入密码" attributes:
                                          @{NSForegroundColorAttributeName:getColor(mainColor)
                                            }];
        _firstTextField.attributedPlaceholder = attrString;
        _firstTextField.leftViewMode = UITextFieldViewModeAlways;
        _firstTextField.secureTextEntry = YES;
        _firstTextField.leftView = ({
            UIImageView *imgView = [UIImageView new];
            imgView.frame = CGRectMake(0, 8, 50, 16);
            imgView.contentMode = 1;
            imgView.image = [UIImage imageNamed:@"password"];
            imgView;
        });
    }
    return _firstTextField;
}

- (UITextField *)secondTextField{
    if (!_secondTextField) {
        _secondTextField  = [[UITextField alloc]init];
        _secondTextField.font = DEF_FontSize_14;
        _secondTextField.textColor = getColor(mainColor);
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"确认密码" attributes:
                                          @{NSForegroundColorAttributeName:getColor(mainColor)
                                            }];
        _secondTextField.attributedPlaceholder = attrString;
        _secondTextField.secureTextEntry = YES;
        _secondTextField.leftViewMode = UITextFieldViewModeAlways;
        _secondTextField.leftView = ({
            UIImageView *imgView = [UIImageView new];
            imgView.frame = CGRectMake(0, 8, 50, 16);
            imgView.contentMode = 1;
            imgView.image = [UIImage imageNamed:@"password"];
            imgView;
        });
    }
    return _secondTextField;
}

- (UITextField *)thirdTextField{
    if (!_thirdTextField) {
        _thirdTextField  = [[UITextField alloc]init];
        _thirdTextField.font = DEF_FontSize_14;
        _thirdTextField.textColor = getColor(mainColor);
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"支付密码" attributes:
                                          @{NSForegroundColorAttributeName:getColor(mainColor)
                                            }];
        _thirdTextField.attributedPlaceholder = attrString;
        _thirdTextField.secureTextEntry = YES;
        _thirdTextField.leftViewMode = UITextFieldViewModeAlways;
        _thirdTextField.leftView = ({
            UIImageView *imgView = [UIImageView new];
            imgView.frame = CGRectMake(0, 8, 50, 16);
            imgView.contentMode = 1;
            imgView.image = [UIImage imageNamed:@"password"];
            imgView;
        });
    }
    return _thirdTextField;
}

- (UIButton *)submitBtn{
    if (!_submitBtn) {
        _submitBtn = [[UIButton alloc]init];
        _submitBtn.titleLabel.font = DEF_FontSize_14;
        [_submitBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_submitBtn setTitleColor:getColor(@"ffffff") forState:UIControlStateNormal];
        _submitBtn.backgroundColor = getColor(mainColor);
        [_submitBtn addTarget:self action:@selector(submitEvent) forControlEvents:UIControlEventTouchUpInside];
        _submitBtn.layer.masksToBounds = YES;
        _submitBtn.layer.cornerRadius = 5;
    }
    return _submitBtn;
}

- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(0, 20 / WIDTH_5S_SCALE, SCREEN_WIDTH, 30 / WIDTH_5S_SCALE)];
        _titleLabel.font = [UIFont systemFontOfSize:50];
        _titleLabel.textColor = getColor(mainColor);
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.text = @"注册";
    }
    return _titleLabel;
}

#pragma mark - layoutFrame

- (void)layoutFrame{
    __weak __typeof(self)weakSelf = self;
    [self.phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
    
    [self.codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(weakSelf.phoneTextField.mas_bottom).offset(1);
        make.height.mas_equalTo(44);
    }];
    
    [self.firstTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(weakSelf.codeTextField.mas_bottom).offset(1);
        make.height.mas_equalTo(44);
    }];
    
    [self.secondTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(weakSelf.firstTextField.mas_bottom).offset(1);
        make.height.mas_equalTo(44 / WIDTH_5S_SCALE);
    }];
    
    [self.thirdTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(weakSelf.secondTextField.mas_bottom).offset(1);
        make.height.mas_equalTo(44 / WIDTH_5S_SCALE);
    }];
    
    [self.submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(- 49 / WIDTH_5S_SCALE);
        make.left.mas_equalTo(49 / WIDTH_5S_SCALE);
        make.top.equalTo(weakSelf.bgView.mas_bottom).offset(10 / WIDTH_5S_SCALE);
        make.height.mas_equalTo(35 / WIDTH_5S_SCALE);
    }];
}

@end
